package chapter15.HomeWork;

import org.junit.Test;

import java.util.*;

/**
 * @Auther: Tx
 * @Date: 2022/5/27 21:46
 */
@SuppressWarnings("all")
public class Homework01 {
    public static void main(String[] args) {
        DAO<User> userDAO = new DAO<>();
        userDAO.save("1", new User(1, 15, "tom"));
        System.out.println(userDAO.get("1"));
        userDAO.update("1", new User(2, 20, "smith"));
        System.out.println(userDAO.get("1"));
        userDAO.save("2",new User(3,50,"jack"));
        System.out.println("-------");
        System.out.println(userDAO.list());
        userDAO.delete("2");
        System.out.println("---------");
        System.out.println(userDAO.list());
    }
}

class DAO<T> {
    Map<String, T> map = new HashMap();

    @Test
    public void save(String id, T entity) {
        map.put(id, entity);
    }

    public T get(String id) {
        return map.get(id);
    }

    public void update(String id, T entity) {
        Set<String> set = map.keySet();
        for (String foundId : set) {
            if (foundId == id) {
                map.put(id, entity);
            }
        }
    }

    public List<T> list() {
        List<T> list = new ArrayList();
        Set<String> set = map.keySet();
//        遍历map得到entity add到list中
        for (String id : set) {
             list.add(map.get(id));
        }
        return  list;

    }

    public void delete(String id) {
        map.remove(id);

    }

    @Override
    public String toString() {
        return "DAO{" +
                "map=" + map +
                '}';
    }
}

class User {
    private int id;
    private int age;
    private String name;

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
